package com.yitiao.multithread.cas;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 在上面的代码中，通过设置最大尝试次数 MAX_RETRIES，
 * 在 CAS 操作中如果超过指定次数仍未成功获取锁，
 * 则放弃 CAS 操作，避免无限自旋造成循环时间长开销大的问题。
 */
public class CASMaxRetriesExample {
    private static AtomicBoolean locked = new AtomicBoolean(false);
    private static final int MAX_RETRIES = 3;

    public static void main(String[] args) {
        new Thread(() -> {
            boolean success = false;
            int retries = 0;

            while (!success && retries < MAX_RETRIES) {
                if (locked.compareAndSet(false, true)) {
                    System.out.println("Thread 1 acquired the lock");
                    success = true;
                } else {
                    retries++;
                    System.out.println("Thread 1 failed to acquire the lock, retrying...");
                }
            }

            if (!success) {
                System.out.println("Thread 1 gave up after " + MAX_RETRIES + " retries");
            }
        }).start();

        new Thread(() -> {
            boolean success = false;
            int retries = 0;

            while (!success && retries < MAX_RETRIES) {
                if (locked.compareAndSet(false, true)) {
                    System.out.println("Thread 2 acquired the lock");
                    success = true;
                } else {
                    retries++;
                    System.out.println("Thread 2 failed to acquire the lock, retrying...");
                }
            }

            if (!success) {
                System.out.println("Thread 2 gave up after " + MAX_RETRIES + " retries");
            }
        }).start();
    }
}
